import _ from 'lodash'
import {tagMap} from './config'
import React, { InputHTMLAttributes } from 'react'

interface mdObject {
  result: Array<mdResult> , 
  src: Array<mdSrc>
}

interface mdSrc {
  index: number,
  content: string,
  used: boolean
}

interface mdResult {
  tag: string,
  content: string
}


/*
{
  h1: "# ",
  h2: "## ",
  h3: "### ",
  hr: "---"
}
*/

export function paragraphSplit (str: string): mdObject {
  const strArr =  str.split("\n")
  const src: Array<mdSrc> = []
  strArr.forEach((item, index) => {
    src.push({index: index,
      content: item,
      used: false})
  })
  return {
    result: [],
    src: src
  }
}

function hParser (tag: string, mdobj: mdObject): mdObject {
  const temp: mdObject = _.cloneDeep(mdobj)
  const mdTag: string = tagMap.get(tag) as string
  temp.src.forEach((item) => {
    if (item.content.startsWith(mdTag)) {
      temp.result[item.index] = {tag: tag, content: item.content.replace(mdTag,"")}
      item.used = true
    }
  })
  temp.src = temp.src.filter(item => !item.used)
  return temp
}

export function normalParser (mdobj: mdObject): mdObject {
  const temp: mdObject = _.cloneDeep(mdobj)
  temp.src.forEach((item) => {
      temp.result[item.index] = {tag: "p", content: item.content}
      item.used = true
  })
  temp.src = temp.src.filter(item => !item.used)
  return temp
}

export const h1Parser = hParser.bind(null, "h1")

export const h2Parser = hParser.bind(null, "h2")

export const h3Parser = hParser.bind(null, "h3")

export function hrParser (mdobj: mdObject): mdObject {
  const temp: mdObject = _.cloneDeep(mdobj)
  temp.src.forEach((item) => {
    if (item.content === "---") {
      temp.result[item.index] = {tag: "hr", content: ""}
      item.used = true
    }
  })
  temp.src = temp.src.filter(item => !item.used)
  return temp
}


export function rElementMap (mdobj: mdObject): Array<React.ReactElement> {
  return mdobj.result.map(item => {
    if (item.content !== "") {
      return React.createElement(item.tag, null, item.content)
    } else {
      return React.createElement(item.tag)
    }
  })
}

export const mdParser = _.flowRight(rElementMap,
                      normalParser,
                      hrParser,
                      h3Parser,
                      h2Parser,
                      h1Parser,
                      paragraphSplit)